#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright: (c)  : @Time 2025/3/30 17  @Author  : hjl
# @Site    :
# @File    : demo2.py
# @Project: alibaba_spider
# @Software: PyCharm
# @Desc    :
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QTableWidget, QTableWidgetItem,
                             QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QLineEdit,
                             QFileDialog, QMessageBox, QDialog, QDialogButtonBox, QCheckBox)
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QUrl, pyqtSignal, QObject
from PyQt5.QtWebEngineWidgets import QWebEnginePage


# 新增：自定义QWebEnginePage类
class CustomWebEnginePage(QWebEnginePage):
    def acceptNavigationRequest(self, url, navigationType, isMainFrame):
        """重写导航请求处理方法"""
        if navigationType == QWebEnginePage.NavigationTypeLinkClicked:
            # 在当前视图中加载链接
            self.setUrl(url)
            return True  # 阻止默认行为
        return super().acceptNavigationRequest(url, navigationType, isMainFrame)


class BrowserWindow(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("阿里巴巴国际站 - 浏览器窗口")
        self.resize(1024, 768)

        # 初始化浏览器并绑定自定义页面
        self.browser = QWebEngineView()
        self.custom_page = CustomWebEnginePage()  # 自定义页面
        self.browser.setPage(self.custom_page)  # 关键步骤！

        # 添加URL变化信号处理
        self.browser.urlChanged.connect(self.handle_url_changed)

        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        self.setLayout(layout)

        # 初始加载页面
        self.load_url("https://www.alibaba.com/")

    def load_url(self, url):
        self.browser.load(QUrl(url))

    def handle_url_changed(self, url):
        """自动打印URL信息"""
        print(f"[浏览器导航] 当前访问URL: {url.toString()}")


class AliCollectorUI(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.browser_windows = []  # 添加浏览器窗口列表

    def initUI(self):
        # 表格
        self.tableWidget = QTableWidget()
        self.tableWidget.setColumnCount(12)
        self.tableWidget.setHorizontalHeaderLabels(["序号", "英文名称", "中文名称", "手机", "座机", "邮箱",
                                                    "公司地址", "城市", "省份", "国家", "联系人", "网址(双击打开)",
                                                    "年份", "信用码"])

        # 模拟数据
        data = [
            ["1", "Company A", "公司A", "13800138000", "010-12345678", "companya@example.com",
             "Address A", "City A", "Province A", "Country A", "Contact A", "http://example.com/a", "2025",
             "1234567890"],
            ["2", "Company B", "公司B", "13900139000", "020-23456789", "companyb@example.com",
             "Address B", "City B", "Province B", "Country B", "Contact B", "http://example.com/b", "2024",
             "0987654321"]
        ]

        # 设置表格行数
        self.tableWidget.setRowCount(len(data))

        # 填充数据到表格
        for row, row_data in enumerate(data):
            for col, cell_data in enumerate(row_data):
                item = QTableWidgetItem(cell_data)
                self.tableWidget.setItem(row, col, item)

        # 条件设置区域
        self.set_condition_label = QLabel("设置搜索条件")
        self.set_condition_label.setStyleSheet("color: red; font-size: 20px; font-family: 'Microsoft YaHei';")

        # 根据商品名搜索
        self.product_name_checkbox = QCheckBox("根据商品名搜索")
        self.product_name_checkbox.setChecked(True)
        self.product_name_input = QLineEdit()

        # 通过浏览器访问抓取
        self.browser_search_button = QPushButton("通过浏览器访问抓取")

        # 采集控制区域
        self.start_collect_button = QPushButton("开始采集")
        self.stop_collect_button = QPushButton("停止采集")
        self.success_count_label = QLabel("成功采集条数： 0")

        # 设置按钮样式
        button_style = "background-color: orange; border-radius: 10px; padding: 5px;"
        self.start_collect_button.setStyleSheet(button_style)
        self.stop_collect_button.setStyleSheet(button_style)

        collect_layout = QHBoxLayout()
        collect_layout.addWidget(self.start_collect_button)
        collect_layout.addWidget(self.stop_collect_button)
        collect_layout.addWidget(self.success_count_label)

        # 数据操作区域
        self.export_button = QPushButton("导出数据")
        self.clear_button = QPushButton("清空数据")

        data_op_layout = QHBoxLayout()
        data_op_layout.addWidget(self.export_button)
        data_op_layout.addWidget(self.clear_button)

        # 搜索条件布局
        search_condition_layout = QHBoxLayout()
        search_condition_layout.addWidget(self.set_condition_label)
        search_condition_layout.addWidget(self.product_name_checkbox)
        search_condition_layout.addWidget(self.product_name_input)
        search_condition_layout.addWidget(self.browser_search_button)

        # 主布局
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.tableWidget)
        main_layout.addLayout(search_condition_layout)
        main_layout.addLayout(collect_layout)
        main_layout.addLayout(data_op_layout)

        self.setLayout(main_layout)
        self.setWindowTitle("崽哥阿里巴巴国际站采集器")
        self.setGeometry(300, 300, 800, 600)

        self.start_collect_button.clicked.connect(self.print_start_collect)
        self.stop_collect_button.clicked.connect(self.print_stop_collect)
        self.export_button.clicked.connect(self.print_export)
        self.clear_button.clicked.connect(self.print_clear)
        # 修改按钮连接信号
        self.browser_search_button.clicked.connect(self.open_browser_window)

    def open_browser_window(self):
        """创建新的浏览器窗口实例"""
        new_window = BrowserWindow(self)
        self.browser_windows.append(new_window)
        new_window.show()
        print("浏览器窗口已打开，开始监控URL变化...")

    def print_login(self):
        print("登录天眼功能被触发")

    def print_start_collect(self):
        print("开始采集链接功能被触发")

    def print_stop_collect(self):
        print("停止采集链接功能被触发")

    def print_collect_phone(self):
        print("采集电话功能被触发")

    def print_export(self):
        print("导出数据功能被触发")

    def print_clear(self):
        print("清空数据功能被触发")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = AliCollectorUI()
    ui.show()
    sys.exit(app.exec_())
